package com.me.launcher.custom;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import com.me.launcher.R;
import com.me.launcher.activity.WorkSpaceFragment;
import com.me.launcher.adapter.GridViewAdapter;
import com.me.launcher.inter.DragStatus;
import com.me.launcher.tools.LogUtil;
import com.me.launcher.tools.ScreenUtils;
import com.me.launcher.tools.Tools;

import static android.content.ContentValues.TAG;
import static com.me.launcher.activity.WorkSpaceFragment.mViewAdapters;
import static com.me.launcher.activity.WorkSpaceFragment.miPageIndex;

/**
 * @author hejiangwei
 */
public class GragGridView extends GridView {
    private static final int DRAG_IMG_SHOW = 1;
    private static final int DRAG_IMG_NOT_SHOW = 0;
    private static final String LOG_TAG = "DragGridView";
    private static final float AMP_FACTOR = 1.2f;
    /**
     * 被拖动的视图
     */
    private ImageView mDragImageView;
    private WindowManager.LayoutParams mDragViewParams;
    private WindowManager mWindowManager;
    private boolean mbIsViewOnDrag = false;
    /**
     * 前一次拖动的位置
     */
    private int preDraggedOverPositon = AdapterView.INVALID_POSITION;
    public  int downRawX;
    private int downRawY;
    private OnDragListener mOnDragListener;
    private Drawable mDrawable;
    private int space;
    private boolean mDraging = false;
    /**
     * 长按选中拖动item
     */
    private OnItemLongClickListener onLongClickListener = new OnItemLongClickListener() {

        @Override
        //长按item开始拖动
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (((GridViewAdapter) getAdapter()).getItem(position).getActivityInfo() == null) {
                return true;
            }
            LogUtil.e(TAG, "onItemLongClick====downRawX==" + downRawX + "==" + (view.findViewById(R.id.img_icon).getLeft() + view.findViewById(R.id.img_icon).getWidth()));

            //getX()获取的是控件相对与父容器的X值，需要加上父容器距离屏幕左边的距离
            float iconLeft=(position%4*(ScreenUtils.getInstance().getScreenW()/4))+view.findViewById(R.id.img_icon).getX();
            if (downRawX < iconLeft || downRawX > (iconLeft + view.findViewById(R.id.img_icon).getWidth())) {
                return true;
            }
            //记录长按item位置
            preDraggedOverPositon = position;

            //获取被长按item的drawing cache
            view.destroyDrawingCache();
            view.setDrawingCacheEnabled(true);
            //通过被长按item，获取拖动item的bitmap
            Bitmap dragBitmap = Bitmap.createBitmap(view.getDrawingCache());

            //设置拖动item为原item 1.2倍
            mDragViewParams.width = dragBitmap.getWidth();//(int) (AMP_FACTOR * dragBitmap.getWidth());
            mDragViewParams.height = dragBitmap.getHeight();//(int) (AMP_FACTOR * dragBitmap.getHeight());
            LogUtil.e(TAG, "onItemLongClick====" + dragBitmap.getWidth() + "==" + dragBitmap.getHeight() + "==" + WorkSpaceFragment.appHeight);
            //设置触摸点为绘制拖动item的中心
            mDragViewParams.x = (downRawX - mDragViewParams.width / 2);
            mDragViewParams.y = (downRawY - mDragViewParams.height / 2 - getResources().getDimensionPixelSize(ScreenUtils.getInstance().getStatusBarHeight()));
//            mDragViewParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
//                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
//                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;


            //dragImageView为被拖动item的容器，清空上一次的显示
            if ((int) mDragImageView.getTag() == DRAG_IMG_SHOW) {
//            if (mDragImageView.isAttachedToWindow()) {
                mWindowManager.removeView(mDragImageView);
                mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
            }
//            }
            //设置本次被长按的item
            mDragImageView.setImageBitmap(dragBitmap);
            //添加拖动item到屏幕
            mWindowManager.addView(mDragImageView, mDragViewParams);
            setFocusable(false);
            setFocusableInTouchMode(false);

            mDragImageView.setTag(DRAG_IMG_SHOW);
            mbIsViewOnDrag = true;
            mDrawable = mDragImageView.getDrawable();
            //设置被长按item不显示
            ((GridViewAdapter) getAdapter()).hideView(position);
            if (mOnDragListener != null) {
                mOnDragListener.onDrag(DragStatus.Drag_start);
                mOnDragListener.onDragApp(((GridViewAdapter) getAdapter()).getItem(position).getActivityInfo().packageName);

            }
            return true;
        }
    };

    public GragGridView(Context context) {
        super(context);
        initView();
    }

    public void initView() {

        setOnItemLongClickListener(onLongClickListener);
        //初始化显示被拖动item的image view
        mDragImageView = new ImageView(getContext());
        mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
        //初始化用于设置dragImageView的参数对象
        mDragViewParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_TOAST,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
//                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
//                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
//                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
// );
        //设置拖动item的参数
        mDragViewParams.gravity = Gravity.TOP | Gravity.LEFT;
        mDragViewParams.format = PixelFormat.TRANSLUCENT;
        mDragViewParams.windowAnimations = 0;


        //获取窗口管理对象，用于后面向窗口中添加dragImageView
        mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        space = (int) (ScreenUtils.getInstance().getScreenH() - ScreenUtils.getInstance().dp2px(20 + 20 + 10 + 5) - getResources().getDimension(R.dimen.x35) - ScreenUtils.getInstance().sp2px(13));
    }

    public GragGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }


    public GragGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    public void setIsViewOnDrag(boolean mbIsViewOnDrag) {
        this.mbIsViewOnDrag = mbIsViewOnDrag;
    }

    public void resetViewOnDrag() {
        preDraggedOverPositon = AdapterView.INVALID_POSITION;
    }

    public void setOnDragListener(OnDragListener listener) {
        mOnDragListener = listener;
    }

    public WindowManager.LayoutParams getDragViewParams() {
        return mDragViewParams;
    }

    public void setDragViewParams(WindowManager.LayoutParams dragViewParams) {
        this.mDragViewParams = dragViewParams;
    }

    public ImageView getDragImageView() {
        return mDragImageView;
    }

    public void setDragImageView(ImageView dragImageView) {

//        mDragImageView.destroyDrawingCache();
//        mDragImageView.setDrawingCacheEnabled(true);
//        //通过被长按item，获取拖动item的bitmap
//        Bitmap dragBitmap = Bitmap.createBitmap(mDragImageView.getDrawingCache());


        this.mDragImageView = dragImageView;
        mbIsViewOnDrag = true;
        mDrawable = this.mDragImageView.getDrawable();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        //被按下时记录按下的坐标
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取触摸点相对于屏幕的坐标
            downRawX = (int) ev.getRawX();
            downRawY = (int) ev.getRawY();
        }
        //dragImageView处于被拖动时，更新dragImageView位置
        else if ((ev.getAction() == MotionEvent.ACTION_MOVE) && (mbIsViewOnDrag == true)) {
            //设置触摸点为dragImageView中心
            if (mOnDragListener != null) {
                mOnDragListener.onDragLocation(ev.getRawX(), ev.getRawY());
            }
            if (ev.getRawX() < 20 || ev.getRawX() > ScreenUtils.getInstance().getScreenW() - 20) {

//                setIsViewOnDrag(false);
                mOnDragListener.onDragNextEvent(ev, ev.getRawX() > ScreenUtils.getInstance().getScreenW() - 20);

                return true;


            }
//            if (Math.abs(ev.getRawX() - mfmoveX) < 20 && Math.abs(ev.getRawY() - mfmoveY) < 20) {
//
//                if (ev.getEventTime() - mTimeMove > 1000) {
//                    Log.e(TAG, "getEventTime===Move==" + ev.getEventTime());
//
//                }
//            } else {
//                mfmoveX = ev.getRawX();
//                mfmoveY = ev.getRawY();
//                mTimeMove = ev.getEventTime();
//            }
            if (ev.getRawY() > space) {
                mOnDragListener.onDragEvent(ev);
                mDraging = true;
                return true;
            } else {
                if (mViewAdapters.get(miPageIndex).isMbSetEmpty()) {
                    mViewAdapters.get(miPageIndex).setRemoveDrag();
                    mOnDragListener.onCancleDragEvent();
                    mDraging = false;
                }

                mDragViewParams.x = (int) (ev.getRawX() - mDragImageView.getWidth() / 2);
                mDragViewParams.y = (int) (ev.getRawY() - mDragImageView.getHeight() / 2 - getResources().getDimensionPixelSize(ScreenUtils.getInstance().getStatusBarHeight()));
                if (!mDragImageView.isAttachedToWindow() || (int) mDragImageView.getTag() != DRAG_IMG_SHOW) {
                    try {
                        mWindowManager.addView(mDragImageView, mDragViewParams);
                        mDragImageView.setTag(DRAG_IMG_SHOW);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    mbIsViewOnDrag = false;
//                    return true;
                }

                //更新窗口显示
                mWindowManager.updateViewLayout(mDragImageView, mDragViewParams);
                //获取当前触摸点的item position

                LogUtil.e(TAG, "onTouchEvent====pointToPosition==" + pointToPosition((int) ev.getRawX(), (int) ev.getRawY()));
                int currDraggedPosition = getPositionIndex(ev.getRawX(), ev.getRawY());
                //如果当前停留位置item不等于上次停留位置的item，交换本次和上次停留的item

                LogUtil.e(TAG, "===currDraggedPosition=="+"==" + currDraggedPosition + "==" + AdapterView.INVALID_POSITION + "==" + preDraggedOverPositon );
                if ((currDraggedPosition != AdapterView.INVALID_POSITION) && (currDraggedPosition != preDraggedOverPositon)) {
//                    if (mbToNext&&){
//                        mViewAdapters.get(miPageIndex).swapView(-1, currDraggedPosition);
//                        preDraggedOverPositon = currDraggedPosition;
//                    }
                    mViewAdapters.get(miPageIndex).swapView(preDraggedOverPositon, currDraggedPosition);
                    preDraggedOverPositon = currDraggedPosition;
                }
            }

        }
        //释放dragImageView
        else if ((ev.getAction() == MotionEvent.ACTION_UP) && (mbIsViewOnDrag == true)) {
            mViewAdapters.get(miPageIndex).setMbSetEmpty(false);
            // 代表滑到其他区域，把事件分发给其他控件
            if (mDraging) {
                mOnDragListener.onDragEvent(ev);
                mDraging = false;

                if ((int) mDragImageView.getTag() == DRAG_IMG_SHOW) {
                    mWindowManager.removeView(mDragImageView);
                    mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
                }
                mbIsViewOnDrag = false;
                return true;
            }

            //代表拖拽滑屏时
            if (mViewAdapters.get(miPageIndex).getHidePosition() < 0) {


                mOnDragListener.onCancleDragNextEvent();

            }
            mViewAdapters.get(miPageIndex).showHideView();
            if ((int) mDragImageView.getTag() == DRAG_IMG_SHOW) {
                mWindowManager.removeView(mDragImageView);
                mDragImageView.setTag(DRAG_IMG_NOT_SHOW);
            }
            if (mOnDragListener != null) {
                mOnDragListener.onDrag(DragStatus.Drag_end);
            }
            preDraggedOverPositon = AdapterView.INVALID_POSITION;
            mbIsViewOnDrag = false;
        }
        return super.onTouchEvent(ev);
    }

    public int getPositionIndex(float moveX, float moveY) {
        int index = 0;
        int indexMax = WorkSpaceFragment.miScreenNum - 1;
        int size = ((int) moveY - WorkSpaceFragment.TopY) / ((WorkSpaceFragment.BottomY - WorkSpaceFragment.TopY) / WorkSpaceFragment.miLinesNum) + 1;
        int remainder = ((int) moveY - WorkSpaceFragment.TopY) % WorkSpaceFragment.miLinesNum;

        if (remainder < ScreenUtils.getInstance().sp2px(13)) {
            index += ((size - 1) * 4);
        } else {
            index += size * 4;
        }
        if (moveX < (ScreenUtils.getInstance().getScreenW() / 4 - WorkSpaceFragment.iconSpace)) {
            index += 0;
        } else if (moveX < (ScreenUtils.getInstance().getScreenW() / 4 + WorkSpaceFragment.iconSpace)) {
            return preDraggedOverPositon;

        } else if (moveX < ScreenUtils.getInstance().getScreenW() / 2 - WorkSpaceFragment.iconSpace) {
            index += 1;
        } else if (moveX < (ScreenUtils.getInstance().getScreenW() / 2 + WorkSpaceFragment.iconSpace)) {
            return preDraggedOverPositon;

        } else if (moveX < ScreenUtils.getInstance().getScreenW() / 4 * 3 - WorkSpaceFragment.iconSpace) {
            index += 2;
        } else if (moveX < (ScreenUtils.getInstance().getScreenW() / 4 * 3 + WorkSpaceFragment.iconSpace)) {
            return preDraggedOverPositon;

        } else {
            index += 3;
        }
//        index+=(int)moveX/(ScreenUtils.getInstance().getScreenW()/4);

        if (index > indexMax) {
            index = -1;
        }
        if (index < 0) {
            index = -1;
        }
        return index;
    }

    //设置变色
    public void setAlphaBitmap(int mColor) {
//          BitmapDrawable mBitmapDrawable = (BitmapDrawable) mContext.getResources().getDrawable(R.drawable.enemy_infantry_ninja);
//          Bitmap mBitmap = mBitmapDrawable.getBitmap();

        //BitmapDrawable的getIntrinsicWidth（）方法，Bitmap的getWidth（）方法
        //注意这两个方法的区别
        //Bitmap mAlphaBitmap = Bitmap.createBitmap(mBitmapDrawable.getIntrinsicWidth(), mBitmapDrawable.getIntrinsicHeight(), Config.ARGB_8888);
        Bitmap mAlphaBitmap = Bitmap.createBitmap(mDragViewParams.width, mDragViewParams.height, Bitmap.Config.ARGB_8888);

        Canvas mCanvas = new Canvas(mAlphaBitmap);
//        PorterDuffColorFilter colorFilter = new PorterDuffColorFilter(mColor, PorterDuff.Mode.MULTIPLY);
        Paint mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
//        mPaint.setColorFilter(colorFilter);
//        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        mPaint.setColor(mColor);
        //从原位图中提取只包含alpha的位图
        Bitmap alphaBitmap = Tools.drawableToBitmap(mDrawable, 1.2f).extractAlpha();
        //在画布上（mAlphaBitmap）绘制alpha位图
        mCanvas.drawBitmap(alphaBitmap, 0, 0, mPaint);
        mDragImageView.setImageBitmap(mAlphaBitmap);


//        ColorFilter filter;
//        filter = new PorterDuffColorFilter(0xFFFF0000, PorterDuff.Mode.SRC_IN);

//        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//        paint.setColorFilter(filter);
//
//        canvas.save();
//        canvas.scale(1.1f, 1.1f,imageCenterX , imageCenterY);
//        canvas.drawBitmap(image, imageX, imageY, paint);
//        canvas.restore();
//
//        canvas.drawBitmap(image, imageX, imageY, null);


//        Bitmap mAlphaBitmap = Bitmap.createBitmap(mDragViewParams.width, mDragViewParams.height, Bitmap.Config.ARGB_8888);
//
//        Canvas mCanvas = new Canvas(mAlphaBitmap);
//        Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
//        ColorMatrix sGhostModeMatrix = new ColorMatrix();
//        sGhostModeMatrix.setSaturation(0);
//
//        // For ghost mode, set the color range to [GHOST_MODE_MIN_COLOR_RANGE, 255]
//        float range = (255 - 10) / 255.0f;
//        ColorMatrix sTempMatrix = new ColorMatrix();
//        sTempMatrix.set(new float[]{
//                range, 0, 0, 0, 0,
//                0, range, 0, 0, 0,
//                0, 0, range, 0, 0,
//                0, 0, 0, range, 0
//        });
//        sGhostModeMatrix.preConcat(sTempMatrix);
//        setBrightnessMatrix(sTempMatrix, 100);
//        sTempMatrix.postConcat(sGhostModeMatrix);
//        mPaint.setColorFilter(new ColorMatrixColorFilter(sTempMatrix));
//        mPaint.setColorFilter(new ColorMatrixColorFilter(sGhostModeMatrix));
//        mCanvas.drawBitmap(Tools.drawableToBitmap(mDrawable, 1.2f), 0, 0, mPaint);
//        mDragImageView.setImageBitmap(mAlphaBitmap);


//        Bitmap mAlphaBitmap = Bitmap.createBitmap( mDragViewParams.width,  mDragViewParams.height, Bitmap.Config.ARGB_8888);
//
//        Canvas mCanvas = new Canvas(mAlphaBitmap);
//        Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
//
//        ColorFilter filter =new PorterDuffColorFilter(Color.argb(100, 255, 255, 255),
//                    PorterDuff.Mode.SRC_ATOP);
//        mPaint.setColorFilter(filter);
//        mCanvas.drawBitmap(Tools.drawableToBitmap(mDrawable,1.2f), 0, 0, mPaint);
//        mDragImageView.setImageBitmap(mAlphaBitmap);
    }

    public void setOriginalBitmap() {
        mDragImageView.setImageDrawable(mDrawable);
    }



    public interface OnDragListener {

        /**
         * 拖拽app的包名
         *
         * @param pkgName
         */
        void onDragApp(String pkgName);


        /**
         * 拖拽状态
         *
         * @param status 开始和结束
         */
        void onDrag(@DragStatus int status);

        /**
         * 根据触摸点 判断是否滑动到删除和应用信息位置
         *
         * @param eventX
         * @param eventY
         */
        void onDragLocation(float eventX, float eventY);

        /**
         * 触摸事件分发给热键区
         *
         * @param ev
         */
        void onDragEvent(MotionEvent ev);

        void onDragNextEvent(MotionEvent ev, boolean isNext);

        /**
         * 拖拽到热键区域的后又回来
         */
        void onCancleDragEvent();

        /**
         * 拖拽到下一页后没有占位就up了
         */
        void onCancleDragNextEvent();
    }
}